<template>
  <div class="min-h-screen bg-#111214">
    <!-- 左侧边栏 - 桌面端 -->
    <div
      class="fixed top-0 left-0 h-100vh transition-all duration-300 overflow-hidden z-999 lt-md:hidden bg-#111214"
      :class="sidebarOpen ? 'w-180px' : 'w-64px'"
    >
      <!-- Logo区域 -->
      <NuxtLink to="/" class="flex justify-center items-center gap-x-5px h-74px bg-#111214">
        <img src="/logo.png" alt="Logo" class="h-28px border-rd-5px" />
        <span v-if="textVisible" class="color-#fff text-24px font-bold logo-text">{{ siteConfig.siteName }}</span>
      </NuxtLink>

      <!-- 侧边栏菜单 -->
      <ul class="sidebar-menu-inner">
        <!-- 首页 -->
        <li :class="route.path === '/' ? 'active' : ''">
          <el-tooltip :disabled="textVisible" effect="dark" content="首页" placement="right">
            <NuxtLink to="/">
              <i class="i-carbon-home w-24px h-24px inline-block"></i>
              <span v-if="textVisible">首页</span>
            </NuxtLink>
          </el-tooltip>
        </li>

        <!-- 动态栏目菜单 -->
        <li
          v-for="item in columns"
          :key="item.columnId"
          :class="route.params.columnValue === item.value ? 'active' : ''"
        >
          <el-tooltip :disabled="textVisible" effect="dark" :content="item.name" placement="right">
            <NuxtLink :to="`/column/${item.value}`">
              <i class="i-carbon-video w-24px h-24px inline-block"></i>
              <span v-if="textVisible">{{ item.name }}</span>
            </NuxtLink>
          </el-tooltip>
        </li>

        <!-- 分割线 -->
        <li class="border-solid border-t-1px border-#ffffff40 m-x-10px"></li>

        <!-- 排行榜 -->
        <li :class="route.path.includes('/trending') ? 'active' : ''">
          <el-tooltip :disabled="textVisible" effect="dark" content="排行榜" placement="right">
            <NuxtLink to="/trending/movie">
              <i class="i-carbon-chart-bar w-24px h-24px"></i>
              <span v-if="textVisible">排行榜</span>
            </NuxtLink>
          </el-tooltip>
        </li>

        <!-- 短视频 -->
        <li :class="route.path.includes('/shorts') ? 'active' : ''">
          <el-tooltip :disabled="textVisible" effect="dark" content="短视频" placement="right">
            <NuxtLink to="/shorts">
              <i class="i-carbon-video-filled w-24px h-24px"></i>
              <span v-if="textVisible">短视频</span>
            </NuxtLink>
          </el-tooltip>
        </li>
      </ul>
    </div>

    <!-- 主内容区 -->
    <div class="main-content transition-all duration-300 lt-md:ml-0px" :class="sidebarOpen ? 'ml-180px' : 'ml-64px'">
      <!-- 顶部栏 - 桌面端 -->
      <div
        :class="sidebarOpen ? 'pl-196px' : 'pl-80px'"
        class="flex w-full bg-[rgba(17,18,20,0.8)] backdrop-blur-sm items-center justify-between gap-10px h-54px fixed left-0 pr-15px z-10 transition-all duration-300 lt-md:hidden"
      >
        <div class="flex items-center gap-10px">
          <!-- 折叠按钮 -->
          <el-icon size="26" color="#f2f2f2" class="cursor-pointer" @click="handleToggleSidebar">
            <component :is="sidebarOpen ? Fold : Expand" />
          </el-icon>

          <!-- 搜索框 -->
          <div class="search-input">
            <input
              v-model="searchKeyword"
              type="text"
              placeholder="搜索影片..."
              autocomplete="off"
              @keyup.enter="handleSearch"
            />
            <NuxtLink :to="`/search?keyword=${searchKeyword}`" class="search-button">
              <el-icon><component :is="Search" /></el-icon>
            </NuxtLink>
          </div>
        </div>

        <!-- 用户菜单 -->
        <div v-if="userStore.userInfo" class="cursor-pointer">
          <el-dropdown @command="handleCommand">
            <el-avatar :size="32" :src="userStore.userInfo.avatar || ''">
              {{ userStore.userInfo.nickName?.charAt(0) || 'U' }}
            </el-avatar>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item disabled>{{ userStore.userInfo.nickName || '用户' }}</el-dropdown-item>
                <el-dropdown-item divided command="center">
                  <i class="i-carbon-user mr-2"></i>个人中心
                </el-dropdown-item>
                <el-dropdown-item command="collection">
                  <i class="i-carbon-star mr-2"></i>我的收藏
                </el-dropdown-item>
                <el-dropdown-item command="history">
                  <i class="i-carbon-time mr-2"></i>观看历史
                </el-dropdown-item>
                <el-dropdown-item divided command="logout">
                  <i class="i-carbon-logout mr-2"></i>退出登录
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
        <div
          v-else
          class="w-88px h-34px bg-#ffffff40 border-rd-8px flex justify-center items-center gap-5px cursor-pointer select-none hover:bg-#ffffff50 transition-colors"
          @click="loginVisible = true"
        >
          <i class="i-carbon-user-filled w-18px h-18px"></i>
          登录
        </div>
      </div>

      <!-- 移动端顶部栏 -->
      <div class="flex justify-between h-58px items-center p-x-20px md:hidden fixed w-full bg-#111214 z-999">
        <NuxtLink to="/" class="flex items-center gap-x-5px">
          <img src="/logo.png" alt="Logo" class="h-28px border-rd-5px" />
          <span class="color-#fff text-20px font-bold logo-text">{{ siteConfig.siteName }}</span>
        </NuxtLink>
        <el-icon size="26" color="#f2f2f2" class="cursor-pointer" @click="mobileSidebarOpen = true">
          <component :is="Expand" />
        </el-icon>
      </div>

      <!-- 移动端内容顶部占位 -->
      <div class="h-58px md:hidden"></div>

      <!-- 页面内容 -->
      <div class="relative">
        <!-- 骨架屏 -->
        <Transition name="skeleton-fade">
          <SkeletonLoader v-if="isPageLoading" :type="pageLoadingType" />
        </Transition>

        <!-- 实际内容 -->
        <div :class="{ 'opacity-0': isPageLoading }">
          <slot />
        </div>
      </div>

      <!-- 底部 -->
      <footer v-if="isShowFooter" class="text-12px color-[rgba(255,255,255,0.6)] m-x-15px mt-20px mb-15px border-solid border-#ffffff40 border-t-1px pt-20px">
        <div class="p-x-5vh m-x-auto text-center">
          <p>{{ siteConfig.siteDescription }}</p>
          <p class="mt-10px">本站仅供测试和学习交流，请大家支持正版。</p>
          <p class="mt-15px">{{ siteConfig.copyright }}</p>
        </div>
      </footer>
    </div>

    <!-- 移动端侧边栏抽屉 -->
    <el-drawer
      v-model="mobileSidebarOpen"
      direction="ltr"
      size="220px"
      :show-close="false"
      class="mobile-drawer"
    >
      <template #header>
        <div class="flex justify-center items-center gap-x-5px">
          <img src="/logo.png" alt="Logo" class="h-34px" />
          <span class="color-#fff text-24px font-bold logo-text">{{ siteConfig.siteName }}</span>
        </div>
      </template>

      <ul class="sidebar-menu-inner">
        <li :class="route.path === '/' ? 'active' : ''">
          <NuxtLink to="/" @click="mobileSidebarOpen = false">
            <i class="i-carbon-home w-24px h-24px inline-block"></i>
            <span>首页</span>
          </NuxtLink>
        </li>

        <li
          v-for="item in columns"
          :key="item.columnId"
          :class="route.params.columnValue === item.value ? 'active' : ''"
        >
          <NuxtLink :to="`/column/${item.value}`" @click="mobileSidebarOpen = false">
            <i class="i-carbon-video w-24px h-24px inline-block"></i>
            <span>{{ item.name }}</span>
          </NuxtLink>
        </li>

        <li class="border-solid border-t-1px border-#ffffff40 m-x-10px"></li>

        <li>
          <NuxtLink to="/trending/movie" @click="mobileSidebarOpen = false">
            <i class="i-carbon-chart-bar w-24px h-24px"></i>
            <span>排行榜</span>
          </NuxtLink>
        </li>

        <li>
          <NuxtLink to="/shorts" @click="mobileSidebarOpen = false">
            <i class="i-carbon-video-filled w-24px h-24px"></i>
            <span>短视频</span>
          </NuxtLink>
        </li>
      </ul>

      <!-- 移动端搜索框 -->
      <div class="search-input mt-10px m-x-10px">
        <input
          v-model="searchKeyword"
          type="text"
          placeholder="搜索影片..."
          autocomplete="off"
          @keyup.enter="handleMobileSearch"
        />
        <NuxtLink :to="`/search?keyword=${searchKeyword}`" class="search-button" @click="mobileSidebarOpen = false">
          <el-icon><component :is="Search" /></el-icon>
        </NuxtLink>
      </div>

      <!-- 移动端用户信息 -->
      <NuxtLink
        v-if="userStore.userInfo"
        to="/user/center"
        class="cursor-pointer absolute bottom-20px right-20px flex items-center gap-x-8px text-12px"
        @click="mobileSidebarOpen = false"
      >
        <el-avatar :size="32" :src="userStore.userInfo.avatar || ''">
          {{ userStore.userInfo.nickName?.charAt(0) || 'U' }}
        </el-avatar>
        {{ userStore.userInfo.nickName }}
      </NuxtLink>
      <div
        v-else
        class="absolute bottom-20px right-20px w-88px h-34px bg-#ffffff40 border-rd-8px flex justify-center items-center gap-5px cursor-pointer select-none"
        @click="handleMobileLogin"
      >
        <i class="i-carbon-user-filled w-18px h-18px"></i>
        登录
      </div>
    </el-drawer>

    <!-- 登录弹窗 -->
    <Login />
  </div>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { Fold, Expand, Search } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()
const siteConfig = useSiteConfig()
const { isPageLoading, pageLoadingType } = usePageLoading()

// 状态管理
const sidebarOpen = useSidebarOpen()
const textVisible = useTextVisible()
const loginVisible = useLoginVisible()
const mobileSidebarOpen = useMobileSidebarOpen()

const searchKeyword = ref('')

// 获取栏目列表
const { data: columns } = await useFetch('/dev-api/app/basic/columns', {
  transform: (res: any) => {
    const list = Array.isArray(res) ? res : (res.data || [])
    // 只返回type=1的内部栏目（影视类型）
    return list.filter((item: any) => item.type === '1' && item.parentId === 0 && item.status === '0')
  }
})

// 折叠/展开侧边栏
const handleToggleSidebar = () => {
  sidebarOpen.value = !sidebarOpen.value
  if (!textVisible.value) {
    setTimeout(() => {
      textVisible.value = true
    }, 300)
  } else {
    textVisible.value = false
  }
}

// 搜索
const handleSearch = () => {
  if (searchKeyword.value.trim()) {
    router.push(`/search?keyword=${searchKeyword.value}`)
  }
}

const handleMobileSearch = () => {
  if (searchKeyword.value.trim()) {
    mobileSidebarOpen.value = false
    router.push(`/search?keyword=${searchKeyword.value}`)
  }
}

// 移动端登录
const handleMobileLogin = () => {
  mobileSidebarOpen.value = false
  loginVisible.value = true
}

// 用户菜单命令
const handleCommand = (command: string) => {
  switch (command) {
    case 'center':
      router.push('/user/center')
      break
    case 'collection':
      router.push('/user/collection')
      break
    case 'history':
      router.push('/user/history')
      break
    case 'logout':
      userStore.logout()
      ElMessage.success('退出成功')
      break
  }
}

// 监听路由变化，关闭移动端侧边栏
watch(() => route.path, () => {
  mobileSidebarOpen.value = false
})

// 是否显示底部
const fullPathArr = ['/column/', '/video/', '/shorts']
const isShowFooter = computed(() => {
  return !fullPathArr.some(path => route.fullPath.includes(path))
})
</script>

<style scoped lang="scss">
// 侧边栏菜单样式
.sidebar-menu-inner {
  li {
    a {
      @apply p-x-12px p-y-10px flex items-center gap-x-10px m-x-8px m-y-2px;
      span {
        @apply color-[rgba(255,255,255,0.8)];
      }
      &:hover {
        background: #2d2f39;
        border-radius: 5px;
      }
    }
    &.active {
      a {
        background: #2d2f39;
        border-radius: 5px;
        position: relative;
        &::before {
          position: absolute;
          content: '';
          background: #00f48e;
          box-shadow: 4px 0 14px 1px #00f48e;
          box-sizing: border-box;
          height: 20px;
          width: 4px;
          border-radius: 2px;
          left: 0;
        }
      }
    }
  }
}

// Logo渐变文字
.logo-text {
  background: linear-gradient(224deg, #fff, #d6ffea);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

// 搜索框样式
.search-input {
  @apply relative flex items-center bg-[rgba(255,255,255,0.1)] border-rd-20px overflow-hidden;
  width: 280px;
  height: 36px;

  input {
    @apply flex-1 bg-transparent border-none outline-none p-x-15px color-#fff text-14px;
    &::placeholder {
      @apply color-[rgba(255,255,255,0.5)];
    }
  }

  .search-button {
    @apply flex items-center justify-center w-36px h-36px cursor-pointer hover:bg-[rgba(255,255,255,0.1)] transition-colors;
    color: rgba(255, 255, 255, 0.8);
  }
}

// 骨架屏过渡样式
.skeleton-fade-enter-active,
.skeleton-fade-leave-active {
  transition: opacity 0.3s ease;
}

.skeleton-fade-enter-from,
.skeleton-fade-leave-to {
  opacity: 0;
}
</style>

<!-- 全局样式（抽屉挂载到body，需要非scoped样式） -->
<style lang="scss">
.mobile-drawer.el-drawer {
  background: #111214 !important;
}
.mobile-drawer .el-drawer__header {
  margin-bottom: 0;
  padding: 20px;
  background: #111214;
  border-bottom: 1px solid rgba(255,255,255,0.1);
}
.mobile-drawer .el-drawer__body {
  padding: 10px;
  background: #111214;
}
</style>
